/*
 * Copyright [2025] [JinBooks of copyright http://www.jinbooks.com]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.jinbooks.web.channel.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jinbooks.authn.annotation.CurrentUser;
import com.jinbooks.entity.Message;
import com.jinbooks.entity.channel.Partner;
import com.jinbooks.entity.channel.dto.PartnerPageDto;
import com.jinbooks.entity.dto.ListIdsDto;
import com.jinbooks.entity.idm.UserInfo;
import com.jinbooks.persistence.service.PartnerService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 渠道/合作方控制器
 *
 * @author your-name
 */
@RestController
@RequestMapping("/partner")
public class PartnerController {
    private static final Logger logger = LoggerFactory.getLogger(PartnerController.class);

    @Autowired
    private PartnerService partnerService;

    /**
     * 分页查询合作方列表
     */
    @GetMapping("/fetch")
    public Message<Page<Partner>> fetch(
            @ParameterObject PartnerPageDto dto,
            @CurrentUser UserInfo currentUser) {
        logger.debug("partner/fetch {}", dto);

        dto.setWorkspaceId(currentUser.getWorkspaceId());
        Page<Partner> page = partnerService.pageList(dto);
        return new Message<>(page);
    }

    /**
     * 获取合作方详情
     *
     * @param id 合作方ID
     * @param currentUser 当前用户
     * @return 合作方详情
     */
    @GetMapping("/get/{id}")
    public Message<Partner> get(
            @PathVariable("id") String id,
            @CurrentUser UserInfo currentUser) {
        logger.debug("partner/get/{} by user: {}", id, currentUser.getUsername());

        Partner partner = partnerService.getById(id);
        if (partner == null) {
            return Message.failed("合作方不存在");
        }

        // 检查是否属于当前工作空间
        if (!currentUser.getWorkspaceId().equals(partner.getWorkspaceId())) {
            return Message.failed("无权访问该合作方");
        }

        return new Message<>(partner);
    }

    /**
     * 添加合作方
     *
     * @param partner 合作方信息
     * @param currentUser 当前用户
     * @return 操作结果
     */
    @PostMapping("/save")
    public Message<String> save(
            @RequestBody Partner partner,
            @CurrentUser UserInfo currentUser) {
        logger.debug("partner/save by user: {}", currentUser.getUsername());

        partner.setWorkspaceId(currentUser.getWorkspaceId());
        boolean success = partnerService.save(partner);

        if (success) {
            return Message.ok("合作方添加成功");
        } else {
            return Message.failed("合作方添加失败");
        }
    }

    /**
     * 更新合作方
     *
     * @param partner 合作方信息
     * @param currentUser 当前用户
     * @return 操作结果
     */
    @PutMapping("/update")
    public Message<String> update(
            @RequestBody Partner partner,
            @CurrentUser UserInfo currentUser) {
        logger.debug("partner/update by user: {}", currentUser.getUsername());

        Partner existingPartner = partnerService.getById(partner.getId());
        if (existingPartner == null) {
            return Message.failed("合作方不存在");
        }

        // 检查是否属于当前工作空间
        if (!currentUser.getWorkspaceId().equals(existingPartner.getWorkspaceId())) {
            return Message.failed("无权更新该合作方");
        }

        partner.setWorkspaceId(currentUser.getWorkspaceId());
        boolean success = partnerService.updateById(partner);

        if (success) {
            return Message.ok("合作方更新成功");
        } else {
            return Message.failed("合作方更新失败");
        }
    }

    /**
     * 删除合作方
     *
     * @param id 合作方ID
     * @param currentUser 当前用户
     * @return 操作结果
     */
    @DeleteMapping("/delete/{id}")
    public Message<String> delete(
            @PathVariable("id") String id,
            @CurrentUser UserInfo currentUser) {
        logger.debug("partner/delete/{} by user: {}", id, currentUser.getUsername());

        Partner partner = partnerService.getById(id);
        if (partner == null) {
            return Message.failed("合作方不存在");
        }

        // 检查是否属于当前工作空间
        if (!currentUser.getWorkspaceId().equals(partner.getWorkspaceId())) {
            return Message.failed("无权删除该合作方");
        }

        boolean success = partnerService.removeById(id);
        if (success) {
            return Message.ok("合作方删除成功");
        } else {
            return Message.failed("合作方删除失败");
        }
    }
    
    /**
     * 批量删除合作方
     *
     * @param dto 合作方ID列表
     * @param currentUser 当前用户
     * @return 操作结果
     */
    @DeleteMapping("/delete")
    public Message<String> deleteBatch(
            @RequestBody ListIdsDto dto,
            @CurrentUser UserInfo currentUser) {
        logger.debug("partner/batch delete by user: {}", currentUser.getUsername());
        
        dto.setWorkspaceId(currentUser.getWorkspaceId());
        boolean success = partnerService.removeByIds(dto.getListIds());
        if (success) {
            return Message.ok("合作方删除成功");
        } else {
            return Message.failed("合作方删除失败");
        }
    }
}